from django.shortcuts import render
from django.http import JsonResponse
from django.utils import timezone
from django.views import View
from django.core.exceptions import ValidationError
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from jobs.models import Position
from jobs import models
import json


# Create your views here.
@method_decorator(csrf_exempt, name='dispatch')
class PositionView(View):

    def get(self, request, position_id=None):  # position_id是可选参数：有值就查单个，没值就查列表
        """查询:单个职位(传ID)或列表"""
        if position_id:
            "根据Id查询单个职位"
            try:
                pos = models.Position.objects.get(id=position_id, is_del=False)
                # 把职位信息转成字典（方便转成JSON给前端）
                data = {
                    "id": pos.id,
                    "name": pos.name,
                    "company": pos.company,
                    "salary_min": pos.salary_min,
                    "salary_max": pos.salary_max,
                    "experience": pos.experience,
                    "status": pos.status,
                    "education": pos.education,
                    "required_skills": pos.required_skills,
                    "description": pos.description,
                    "publish_time": pos.publish_time.strftime("%Y-%m-%d"),
                    "creator_id": pos.creator_id,
                }
                return JsonResponse({"code": 200, "data": data, "msg": "职位获取成功"})
            except Position.DoesNotExist:
                # 没找到对应ID的职位，返回404错误
                return JsonResponse({"code": 404, "msg": "职位不存在"})
        else:
            # 查询列表（支持按状态筛选）
            status = request.GET.get("status")
            # 获取所有职位
            positions = Position.objects.filter(is_del=False)
            if status:
                positions = positions.filter(status=status)
            # 把列表转成字典列表（只返回部分关键信息）
            data_list = [{
                "id": pos.id,
                "name": pos.name,
                "company": pos.company,
                "publish_time": pos.publish_time.strftime("%Y-%m-%d")
            } for pos in positions]
            return JsonResponse({"code": 200, "data": data_list, "msg": "职位列表获取成功"})

    def post(self, request):
        """创建职位"""
        try:
            # 把前端发过来的JSON数据转成字典
            data = json.loads(request.body)
            # 创建职位对象
            pos = Position(
                name=data["name"],
                company=data["company"],
                salary_min=data["salary_min"],
                salary_max=data["salary_max"],
                experience=data["experience"],
                education=data["education"],
                required_skills=data["required_skills"],
                description=data["description"],
                creator_id=data["creator_id"],
                status="上架",
                publish_time=timezone.now(),
                is_del=False
            )
            pos.full_clean()  # 触发数据校验（包括clean方法）
            pos.save()
            return JsonResponse({"code": 201, "msg": "职位发布成功", "data": {"id": pos.id}})
        except KeyError as e:
            return JsonResponse({"code": 400, "msg": f"缺少字段：{e}"}, status=400)
        except ValidationError as e:
            return JsonResponse({"code": 400, "msg": f"数据无效：{e}"}, status=400)

    def put(self, request, position_id):
        """更新职位"""
        try:
            pos = Position.objects.get(id=position_id, is_del=False)
            data = json.loads(request.body)
            # 更新字段（仅更新传入的字段）
            for key, value in data.items():
                # 检查这个字段是否是职位有的（防止乱传字段），并且不能改ID和发布时间
                if hasattr(pos, key) and key not in ["id", "publish_time"]:  # 禁止修改ID和发布时间
                    setattr(pos, key, value)  # 相当于 pos.字段名 = 新值
            pos.full_clean()  # 校验更新后的数据
            pos.save()
            return JsonResponse({"code": 200, "msg": "职位更新成功"})
        except Position.DoesNotExist:
            return JsonResponse({"code": 404, "msg": "职位不存在"}, status=404)
        except ValidationError as e:
            return JsonResponse({"code": 400, "msg": f"数据无效：{e}"}, status=400)

    def delete(self, request, position_id):
        """删除职位"""
        try:
            pos = models.Position.objects.get(id=position_id)
            pos.is_del = True
            pos.save()
            return JsonResponse({"code": 200, "msg": "职位删除成功"})
        except Position.DoesNotExist:
            return JsonResponse({"code": 404, "msg": "职位不存在"}, status=404)

    def patch(self, request, position_id):
        """处理职位状态更新(上架/下架)和刷新逻辑"""
        try:
            pos = models.Position.objects.get(id=position_id, is_del=False)
            data = json.loads(request.body)
            # 允许的参数列表
            allowed_keys = ["status", "refresh"]
            # 检查是否有无效参数
            for key in data.keys():
                if key not in allowed_keys:
                    return JsonResponse({"code": 400, "msg": f"请求参数错误,允许的参数:{allowed_keys}"},
                                        status=400)  # 验证请求参数是否合法
            if "status" in data:
                valid_status = ["上架", "下架"]
                if data["status"] not in valid_status:
                    return JsonResponse({"code": 400, "msg": f"状态值无效,可选值:{valid_status}"}, status=400)
                pos.status = data["status"]
            if "refresh" in data:
                if not isinstance(data["refresh"], bool):
                    return JsonResponse({"code": 400, "msg": "refresh必须为布尔值"}, status=400)
                if data["refresh"] is True:
                    pos.publish_time = timezone.now()  # 刷新发布时间为当前时间
            pos.full_clean()  # 校验数据是否符合规则
            pos.save()
            return JsonResponse({"code": 200, "msg": "操作成功"})
        except models.Position.DoesNotExist:
            return JsonResponse({"code": 404, "msg": "职位不存在"}, status=404)
        except ValidationError as e:
            return JsonResponse({"code": 400, "msg": f"数据无效：{e}"}, status=400)
        except json.JSONDecodeError:
            return JsonResponse({"code": 400, "msg": "无效的JSON数据"}, status=400)
